<template>
  <div class="login-form">
    <!-- 标题区域(提示文字是告诉用户切换xxxx登录方式) -->
    <div class="toggle">
      <a href="javascript:;" v-if="isMsgLogin" @click="changeLoginTypeFn(false)">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" v-else @click="changeLoginTypeFn(true)">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <!-- 表单区域 -->
   <div class="form">
      <my-form autocomplete="off" ref="target" :validation-schema="formSchema">
        <template v-if="!isMsgLogin">
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-user"></i>
              <my-field
                type="text"
                name="account"
                placeholder="请输入账号"
                v-model="form.account"
              />
            </div>
            <!-- <div class="error"><i class="iconfont icon-warning" />请输入手机号</div> -->
            <ErrorMessage name="account" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
          </div>
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-lock"></i>
              <my-field
                type="password"
                name="password"
                placeholder="请输入密码"
                v-model="form.password"
              />
            </div>
            <ErrorMessage name="password" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
          </div>
          <div class="form-item">
          <div class="agree">
            <!-- 自定组件：as XtxCheckbox 指定渲染的组件 -->
            <my-field name="isAgree" v-model="form.isAgree" as="xtx-checkbox"  />
            <span>我已同意</span>
            <a href="javascript:;">《隐私条款》</a>
            <span>和</span>
            <a href="javascript:;">《服务条款》</a>
          </div>
          <ErrorMessage name="isAgree" v-slot="{ message }">
            <div class="error" v-if="message">
              <i class="iconfont icon-warning" />{{ message }}
            </div>
          </ErrorMessage>
        </div>
        </template>
        <template v-else>
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-user"></i>
              <my-field
                type="text"
                name="mobile"
                placeholder="请输入手机号"
                v-model="form.mobile"
              />
            </div>
            <ErrorMessage name="mobile" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
          </div>
          <div class="form-item">
            <div class="input">
              <i class="iconfont icon-code"></i>
              <my-field
                type="text"
                name="code"
                placeholder="请输入验证码"
                v-model="form.code"
              />
              <span class="code" @click="sendFn">{{ time > 0 ? `倒计时${time}秒` : '发送验证码' }}</span>
            </div>
            <ErrorMessage name="code" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
          </div>
          <div class="form-item">
          <div class="agree">
            <!-- 自定组件：as XtxCheckbox 指定渲染的组件 -->
            <my-field name="isAgree" v-model="form.isAgree" as="xtx-checkbox"  />
            <span>我已同意</span>
            <a href="javascript:;">《隐私条款》</a>
            <span>和</span>
            <a href="javascript:;">《服务条款》</a>
          </div>
          <ErrorMessage name="isAgree" v-slot="{ message }">
            <div class="error" v-if="message">
              <i class="iconfont icon-warning" />{{ message }}
            </div>
          </ErrorMessage>
        </div>
        </template>
        <a href="javascript:;" class="btn" @click="loginFn">登录</a>
      </my-form>
    </div>
    <!-- 底部 -->
    <div class="action">
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, reactive, watch } from 'vue'
import { Form, Field, ErrorMessage } from 'vee-validate'
import schema from '@/utils/schema'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import Message from 'erabbit-ui/packages/components/Message'
import { useIntervalFn } from '@vueuse/core'
import { getCodeAPI, loginByCodeAPI } from '@/api'
export default {
  name: 'LoginForm',
  components: {
    // 组件标签名: 组件对象
    MyForm: Form,
    MyField: Field,
    ErrorMessage
  },
  setup () {
    const store = useStore()
    const router = useRouter()
    const isMsgLogin = ref(false) // 记录是否以短信登录状态输入框(true是, false不是)-默认上来以账号密码登录
    const target = ref(null) // 绑定Form组件对象
    const form = reactive({ // 收集表单对象
      isAgree: false,
      mobile: null,
      account: null,
      password: null,
      code: null
    })

    // 发送验证码-倒计时效果
    const time = ref(0) // 剩余的时间
    // pause函数: 用于暂停计时器
    // resume函数: 用于启动计时器
    // isActive: 当前计时器是否处于激活状态
    const { pause, resume, isActive } = useIntervalFn(() => {
      // 间隔一秒执行一次(必须resume调用后开始执行)
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000)

    // 发送验证码按钮->点击事件
    const sendFn = () => {
      const result = schema.mobile(form.mobile)
      if (result === true) {
        if (isActive.value === false) {
          time.value = 60
          resume() // 执行倒计时
          getCodeAPI({
            mobile: form.mobile
          }).catch(() => {
            Message({
              type: 'error',
              text: '检查手机号, 默认只能是13888888888'
            })
          })
        }
      } else {
        Message({
          type: 'error',
          text: '请填写手机号'
        })
      }
    }

    // 切换登录方式
    const changeLoginTypeFn = (bool) => {
      isMsgLogin.value = bool
    }

    // 做表单校验
    // 思考: utils/schema.js 是我们整个项目所有表单的校验规则大对象
    // 只解构出来当前登录表单验证需要的5个方法
    const { account, password, mobile, code, isAgree } = schema
    // 接着再组织当前页面需要检验规则对象
    const formSchema = { account, password, mobile, code, isAgree }

    // 登录->点击事件
    const loginFn = async () => {
      // 做Form表单整体(兜底)校验
      const res = await target.value.validate()
      if (res) {
        // 通过-整体表单校验
        if (isMsgLogin.value === true) {
          try {
            const res = await loginByCodeAPI({
              mobile: form.mobile,
              code: form.code
            })
            store.commit('user/SET_USER', res.result)
            Message({
              type: 'success',
              text: '登录成功'
            })
            router.replace('/')
            await store.dispatch('cart/uploadMergeCartListActions')
            store.dispatch('cart/getAllCartListActions')
          } catch (err) {
            Message({
              type: 'error',
              text: '验证码错误'
            })
          }
        } else {
          try {
            await store.dispatch('user/loginActions', {
              account: form.account,
              password: form.password
            })
            Message({
              type: 'success',
              text: '登录成功'
            })
            router.replace('/')
            await store.dispatch('cart/uploadMergeCartListActions')
            store.dispatch('cart/getAllCartListActions')
          } catch (err) {
            Message({
              type: 'error',
              text: '登录失败_请检查账号密码'
            })
          }
        }
      } else {
        Message({
          type: 'error',
          text: '必选项错误'
        })
      }
    }

    // 侦听登录方式改变->清空表单输入框值
    watch(isMsgLogin, () => {
      form.isAgree = false
      form.mobile = null
      form.account = null
      form.password = null
      form.code = null

      target.value.resetForm() // 可以重置整个表单(包括内容和校验规则提示)
    })

    return {
      isMsgLogin,
      changeLoginTypeFn,
      form,
      formSchema,
      target,
      loginFn,
      sendFn,
      time
    }
  }
}
</script>
<style lang="less" scoped>
// 账号容器
.login-form {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: var(--xtx-color);
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: var(--price-color);
          }
          &.active,
          &:focus {
            border-color: var(--xtx-color);
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: var(--price-color);
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: var(--xtx-color);
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
